package com.wanghua.mall.coupon.service.impl;

import com.wanghua.mall.coupon.entity.SeckillSkuRelationEntity;
import com.wanghua.mall.coupon.service.SeckillSkuRelationService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;

import com.wanghua.mall.coupon.dao.SeckillSessionDao;
import com.wanghua.mall.coupon.entity.SeckillSessionEntity;
import com.wanghua.mall.coupon.service.SeckillSessionService;

import javax.annotation.Resource;


@Service
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Resource
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 扫描最近三天的活动
     *
     * @return
     */
    @Override
    public List<SeckillSessionEntity> getLatestThreeDaySession() {
        //最近三天
        LocalDate now = LocalDate.now();
        List<SeckillSessionEntity> list = baseMapper
                .selectList(new QueryWrapper<SeckillSessionEntity>()
                        .between("start_time", getStartTime(), getEndTime()));
        if (list != null && list.size() > 0) {
            for (SeckillSessionEntity entity : list) {
                entity.setRelationSkuList(seckillSkuRelationService
                        .list(new QueryWrapper<SeckillSkuRelationEntity>()
                                .eq("promotion_session_id", entity.getId())));
            }
        }
        return list;
    }

    /**
     * 获得开始时间
     * 2021-09-11 00:00:00
     *
     * @return
     */
    private String getStartTime() {
        LocalDateTime time = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获得结束时间
     * 2021-09-13 23:59:59
     *
     * @return
     */
    private String getEndTime() {
        LocalDateTime time = LocalDateTime.of(LocalDate.now().plusDays(2L), LocalTime.MAX);
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    }

}